layui.define(['zlContext', 'layer', 'zlConfig','form'], function (exports) {
    var $ = layui.$
        , zlContext = layui.zlContext
        , layer = layui.layer
        , zlConfig = layui.zlConfig
        , form = layui.form // 回调函数使用
        , isloadsearch = false;
    layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.WM_DRAW, null, function (WParam) {
        if (WParam && $(WParam.elem).attr('class') && $(WParam.elem).attr('class').indexOf('zlpoptree') >= 0) {
            zlpoptree.render($(WParam.elem), WParam.value, $(WParam.elem).attr('text'));
        }
    });
    zlpoptree = {
        render: function ($elem, value, text) {
            var tempvalue = (value == undefined ? ($elem.attr('value') ? $elem.attr('value') : '') : value)
                , temptext = text == undefined ? "" : text
                , name = $elem.attr('name')
                , divname = 'div' + name
                , inputname = 'input' + name
                , successcallback = $elem.attr('callback');
            if ($elem.attr('loaded') && tempvalue == $('input[name="' + name + '"]').val()) {
                return;
            }

            var defaultsetting = {
                selectedMulti: false,
                view: {
                    multselect: true,
                },
                formtitle: "选择树节点",
                ischeckleaf: false,
                id: 'RWID',
                sourcedata: undefined,
                edittype: 'edit',
                check: {
                    enable: false,
                    autoCheckTrigger: true,
                    chkboxType: { "Y": "", "N": "" },
                    chkStyle: "checkbox",
                },
                view: {
                    showLine: true
                },
                async: {
                    enable: true,
                    type: "post",
                    dataFilter: function ajaxDataFilter(treeId, parentNode, responseData) {
                        if (responseData[zlConfig.global.result.statusName] == 'OK') {
                            var data = responseData[zlConfig.global.result.dataName];
                            for (var i = 0; i < data.length; i++) {
                                data[i].icon = layui.cache['contentPath'] + "/static/image/fun.png";
                            }
                            return data;
                        }
                        else {
                            zlContext.errorMsg(responseData[zlConfig.global.result.msgName]);
                        }
                        return responseData;
                    }
                },
                data: {
                    key: {
                        name: "OBJNAME"
                    }
                    , simpleData: {
                        enable: true
                        , idKey: "RWID"
                        , pIdKey: "SYS_PARENTID"
                        , rootPid: ""
                    }

                },
                selectcallback: function (data, options) {
                    if (data == undefined) {
                        return;
                    }
                    if (!options.multselect) {
                        $('input[name="' + options.inputhiddename + '"]').val(data[0][options.data.simpleData.idKey]);
                        $('input[name="' + options.inputname + '"]').val(data[0][options.data.key.name]);
                    } else {
                        var id = ""
                            , name = "";
                        for (var i = 0; i < data.length; i++) {
                            id = id + "," + data[i][options.data.simpleData.idKey];
                            name = name + "," + data[i][options.data.key.name];
                        }
                        id = id.substr(1, id.length);
                        name = name.substr(1, name.length);
                        $('input[name="' + options.inputhiddename + '"]').val(id);
                        $('input[name="' + options.inputname + '"]').val(name);
                    }
                    if (successcallback) {
                        zlpoptree.doCallback(successcallback, data);
                    }
                },
                callback: {
                    beforeAsync: function (treeId, treeNode) {
                        // newoptions.loadingLayer = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
                        zlpoptree.partialMsg('ultreebox', '数据查询中，请稍候...', '16');
                    },
                    onAsyncSuccess: function (event, treeId, treeNode, msg) {
                        zlpoptree.setcheck(treeId, $elem.attr('name'), newoptions);
                        // layer.close( newoptions.loadingLayer)
                        $('#ultreebox').find('.partialMsg').remove();
                    },
                    onDblClick: function (event, treeId, treeNode) {
                        if (newoptions.check.enable == false && !treeNode.isParent) {
                            layer.close(newoptions.formindex);
                            var data = new Array();
                            data.push(treeNode);
                            newoptions.selectcallback(data, newoptions);
                            if (successcallback) {
                                zlpoptree.doCallback(successcallback, data);
                            }
                        }
                    },
                    beforeClick: function (treeId, treeNode, clickFlag) {
                        if (newoptions.ischeckleaf) {
                            return !treeNode.isParent;//当是父节点 返回false 不让选取
                        } else {
                            return true;
                        }

                    }
                }
            }

                , inputhiddename = name
                , $parent = $elem.parent()
                , options = ($elem.attr('settings') != "" ? eval('(' + $elem.attr('settings') + ')') : {})
                , url = options.dataurl
                , sourcedata = options.sourcedata
                , placeholder = options.placeholder == undefined ? "" : options.placeholder
                , newoptions
                , tempverify = $elem.attr('verify') == undefined ? "" : $elem.attr('verify')
                , addspanid = name + 'addspan'
                , delspanid = name + 'delspan'
                , objname = ""
                , value = tempvalue
                , readonly = $elem.attr('disabled') ? 'disabled' : ''
                , mouseShow = $elem.attr('disabled') ? 'not-alowed' : 'pointer'
                , html = [
                    , '<div class = "layui-select-title" name="' + divname + '">'
                    , '     <input type="text" class="layui-input" placeholder ="' + placeholder + '" name="' + inputname + '" readonly ' + readonly + ' lay-verify="' + tempverify + '"  value="' + temptext + '" style="cursor: ' + mouseShow + '">'
                    , '</div>']
                , parenthtml = [
                    , '<input type="hidden" class="layui-input" name="' + inputhiddename + '" value="' + tempvalue + '">'];
            if (url == undefined && sourcedata == undefined) {
                zlContext.errorMsg('未找到数据或数据源链接！')
                return;
            }
            $elem.attr('loaded', 1);
            $elem.empty();
            $('input[name="' + inputhiddename + '"]').remove();
            $elem.append(html.join(''));
            $parent.append(parenthtml.join(''));
            newoptions = $.extend({}, defaultsetting, options);
            if (newoptions.edittype == 'edit') {
                $('div[name="' + divname + '"]').append(' <i class="layui-icon layui-icon-more layui-i-add" id="' + addspanid + '"></i> ' + '     <i class="layui-icon layui-icon-close layui-i-del" id="' + delspanid + '"></i> ')
            }
            if (url == undefined) {
                newoptions.sourcedata = eval('(' + sourcedata + ')');
            } else {
                newoptions.async.enable = true;
                newoptions.async.url = url;
                newoptions.async.otherParam = eval('(' + (options.params) + ')');
                newoptions.async.type = options.method == undefined ? newoptions.async.type : options.method;
            }
            newoptions.check.enable = options.checkbox == undefined ? false : options.checkbox
            if (newoptions.check.enable) {
                newoptions.check.chkboxType = options.chkboxType == undefined ? newoptions.check.chkboxType : eval('(' + options.chkboxType + ')');
            }
            newoptions.data.key.name = options.name == undefined ? newoptions.data.key.name : options.name;
            newoptions.data.simpleData.idKey = options.idKey == undefined ? newoptions.data.simpleData.idKey : options.idKey;
            newoptions.data.simpleData.pIdKey = options.pIdKey == undefined ? newoptions.data.simpleData.pIdKey : options.pIdKey;
            newoptions.inputhiddename = inputhiddename;
            newoptions.inputname = inputname;
            newoptions.elemname = name;

            if (zlContext.isEmpty(text) && !zlContext.isEmpty(value)) {
                if (!zlContext.isEmpty(url)) {
                    var valuelist = new Array()
                        , tempvalue = value;
                    newoptions.async.otherParam = (newoptions.async.otherParam == undefined ? {} : newoptions.async.otherParam);
                    if (tempvalue) {
                        newoptions.async.otherParam[newoptions.id] = tempvalue;
                    }                    
                    $.ajax({
                        url: url,
                        type: newoptions.async.type,
                        async: false,
                        data: newoptions.async.otherParam,
                        dataType: 'json',
                        success: function (result) {
                            var sourcedata = result.obj;
                            for (var i = 0; i < sourcedata.length; i++) {
                                if (tempvalue.indexOf(sourcedata[i][newoptions.id]) > -1) {
                                    objname = objname + "," + sourcedata[i][newoptions.data.key.name]
                                }
                            }
                            objname = objname.substr(1, objname.length);
                            $('input[name="' + inputname + '"]').val(objname);
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {

                        },
                        complete: function (XMLHttpRequest, textStatus) {
                        }
                    });
                } else {
                    for (var i = 0; i < newoptions.sourcedata.length; i++) {
                        if (tempvalue.indexOf((newoptions.sourcedata)[i][newoptions.id] > -1)) {
                            objname = objname + "," + (newoptions.sourcedata)[i][newoptions.data.key.name]
                        }
                    }
                    objname = objname.substr(1, objname.length);
                    $('input[name="' + inputname + '"]').val(objname);
                }
            }
            newoptions.async.otherParam = eval('(' + (options.params) + ')');
            if (newoptions.edittype == 'edit') {
                zlpoptree.initspan(newoptions, addspanid, delspanid,successcallback);
            }
        },
        initspan: function (options, addspanid, delspanid,successcallback) {
            options = options || {};
            var treeobj;
            $input = $('input[name="' + options.inputname + '"]');
            $('#' + delspanid).hide();
            $input.on('mouseenter', function () {
                if ($(this).val() != "") {
                    $('#' + delspanid).show();
                }
            });
            $input.on('mouseleave', function () {
                $('#' + delspanid).hide();
            });
            $('#' + delspanid).on('mouseenter', function () {
                $('#' + delspanid).show();
            });
            $('#' + delspanid).on('mouseleave', function () {
                $('#' + delspanid).hide();
            });
            $('input[name="' + options.inputname + '"]').on('click', function () {
                $('#' + addspanid).trigger('click');
            });
            $('#' + addspanid).on('click', function () {
                if ($(this).parents('.zlpoptree').attr('disabled')) return
                var objlist = new Array();
                var html = [
                    '<div class="layui-form" style="height: 30px;padding: 8px 0; margin:0 10px; position: relative;">'
                    , '    <button class="layui-btn layui-btn-sm layui-btn-normal" id="seacher" style="position: absolute;right: 0px;">'
                    , '        <i class="layui-icon" style="margin-right: 0;">&#xe615;</i>'
                    , '    </button>'
                    , '    <input type="text"  placeholder="请输入查找的节点值" id="keyvalue" autocomplete="on" class="layui-input" style="width:100%;height: 30px;margin-left:0px;padding-right:40px">'
                    , '</div>'
                    , '<div id="ultreebox" class="layui-card-body ultreebox" style="height:calc(100% - 58px); padding:0; margin:0 10px; overflow: auto;border:1px solid #eee;">'
                    , '    <ul id="' + options.name + 'poptree" class="ztree layui-layer-page" style="width: 100%;padding: 5px 8px;box-sizing: border-box;"></ul>'
                    , '</div>'];
                options.formindex = layer.open({
                    type: 1,
                    id: 'zlpoptreeLayer',
                    area: ['500px', '80%'],
                    // maxHeight: 500,
                    offset: '10%',
                    content: html.join(''),
                    title: options.formtitle == undefined ? "树形信息" : options.formtitle,
                    btn: ['确定', '取消'],
                    success: function (layero, index) {
                        $(".ultreebox").height(layero.find('.layui-layer-content').height() - 58)
                        var nodeList;
                        if (options.sourcedata != undefined) {
                            treeobj = $.fn.zTree.init($("#" + options.name + "poptree"), options, options.sourcedata);
                            zlpoptree.setcheck(options.name + "poptree", options.inputhiddename, options);
                        } else {
                            treeobj = $.fn.zTree.init($("#" + options.name + "poptree"), options, null);
                        }

                        $('#seacher').on('click', function () {
                            var text = $('#keyvalue').val();
                            isloadsearch = true;
                            searchNode(text);
                        });
                        $("#keyvalue").keyup(function () {
                            var e = event || window.event;
                            if (e.keyCode == 13) {
                                $("#seacher").trigger("click");
                                isloadsearch = true;
                            }
                            if ((e.keyCode == '46' || e.keyCode == '8' || (e.ctrlKey && e.keyCode == '86')) && $(this).val() == '' && isloadsearch) {
                                $("#seacher").trigger("click");
                                isloadsearch = false;
                            }
                        });
                        function searchNode(value) {
                            var keyType = options.data.key.name;
                            if (value === "") {
                                var allNode = treeobj.transformToArray(treeobj.getNodes());
                                treeobj.showNodes(allNode);
                                zlContext.noData($('#' + treeobj.setting.treeId), true)
                                return;
                            }
                            nodeList = treeobj.getNodesByParamFuzzy(keyType, value);
                            nodeList = treeobj.transformToArray(nodeList);
                            updateNodes(true, value, keyType);
                        };
                        function updateNodes(highlight, value, keyType) {
                            var allNode = treeobj.transformToArray(treeobj.getNodes());
                            treeobj.hideNodes(allNode);
                            for (var n = 0; n < nodeList.length; n++) {
                                findParent(treeobj, nodeList[n]);
                            }
                            treeobj.showNodes(nodeList);
                            nodeList = treeobj.getNodesByParamFuzzy(keyType, value);
                            for (var i = 0; i < nodeList.length; i++) {
                                treeobj.updateNode(nodeList[i]);
                            }
                            if (treeobj.getNodesByParam('isHidden', false, null).length == 0) {
                                zlContext.noData($('#' + treeobj.setting.treeId))
                            }
                        };
                        function findParent(zTree, node) {
                            zTree.expandNode(node, true, false, false);
                            var pNode = node.getParentNode();
                            if (pNode != null) {
                                nodeList.push(pNode);
                                findParent(zTree, pNode);
                            }

                        };
                    },
                    yes: function (index) {
                        objlist = [];
                        var selectnode = treeobj.getSelectedNodes();
                        var cancontinue = true;
                        if (options.check != undefined && options.check.enable) {
                            selectnode = treeobj.getCheckedNodes(true);
                        }
                        if (selectnode.length == 0) {
                            zlContext.warnMsg(options.errmsg == undefined ? "请选择树节点" : options.errmsg);
                            return;
                        }
                        var ischeckleaf = options.ischeckleaf;
                        for (var i = 0; i < selectnode.length; i++) {
                            var treenode = selectnode[i];
                            if (treenode.children != undefined && ischeckleaf) {
                                zlContext.warnMsg("请选择树的叶子节点！");
                                cancontinue = false;
                                return;
                            }
                            if (objlist.length == 1 && options.multselect == false) {
                                zlContext.warnMsg("只能选择一个节点！");
                                cancontinue = false;
                                return;
                            }
                            objlist.push(treenode);
                        }
                        layer.close(index);
                        if (cancontinue) {
                            if (options.selectcallback != undefined) {
                                options.selectcallback(objlist, options);
                            } else {
                                return objlist;
                            }
                        } else {
                            return;
                        }
                    },
                });
            });
            $('#' + delspanid).on('click', function () {
                $('input[name="' + options.inputhiddename + '"]').val("");
                $('input[name="' + options.inputname + '"]').val("");
                if(successcallback){
                    zlpoptree.doCallback(successcallback,null);
                }
            });
        },
        setcheck: function (treeId, inputname, setting) {
            var ids = $('input[name="' + inputname + '"]').val()
                , treeobj = $.fn.zTree.getZTreeObj(treeId)
                , nodeList = treeobj.transformToArray(treeobj.getNodes());
            if (ids != undefined) {
                //"3755ACF68000000179D521FDB917E091"
                for (var i = 0; i < nodeList.length; i++) {
                    if (ids.indexOf(nodeList[i][setting.id]) > -1) {
                        if (setting.check.enable) {
                            nodeList[i].checked = true;
                            treeobj.updateNode(nodeList[i]);
                        } else {
                            treeobj.selectNode(nodeList[i]);
                            break;
                        }
                    }
                }
            }
        },
        onlyshow: function (options) {
            var objlist = new Array();
            var html = ['<div class="layui-form">'
                , '<ul id="poptree" class="ztree"></ul>'
                , '</div>'];
            layer.open({
                type: 1,
                area: ['450px', '450px'],
                content: html.join(''),
                title: options.formtitle == undefined ? "树形信息" : options.formtitle,
                success: function () {
                    treeobj = $.fn.zTree.init($("#poptree"), options, null);
                },
            });
        },
        clickShow: function (options) {
            var html = [
                '<div class="layui-form" style="height: 30px;padding: 8px 0; margin:0 10px; position: relative;">'
                , '    <button class="layui-btn layui-btn-sm layui-btn-normal" id="seacher" style="position: absolute;right: 0px;">'
                , '        <i class="layui-icon" style="margin-right: 0;">&#xe615;</i>'
                , '    </button>'
                , '    <input type="text"  placeholder="请输入查找的节点值" id="keyvalue" autocomplete="on" class="layui-input" style="width:100%;height: 30px;margin-left:0px;padding-right:40px">'
                , '</div>'
                , '<div id="ultreebox" class="layui-card-body ultreebox" style="height:calc(100% - 58px); padding:0; margin:0 10px; overflow: auto;border:1px solid #eee;">'
                , '    <ul id="' + options.name + 'poptree" class="ztree layui-layer-page" style="width: 100%;padding: 5px 8px;box-sizing: border-box;"></ul>'
                , '</div>'];
            options.formindex = layer.open({
                type: 1,
                id: 'zlpoptreeLayer',
                area: ['500px', '80%'],
                // maxHeight: 500,
                offset: '10%',
                content: html.join(''),
                title: options.formtitle == undefined ? "树形信息" : options.formtitle,
                btn: ['确定', '取消'],
                success: function (layero, index) {
                    $(".ultreebox").height(layero.find('.layui-layer-content').height() - 58)
                    var nodeList;
                    if (options.sourcedata != undefined) {
                        treeobj = $.fn.zTree.init($("#" + options.name + "poptree"), options, options.sourcedata);
                    } else {
                        treeobj = $.fn.zTree.init($("#" + options.name + "poptree"), options, null);
                    }
                    $('#seacher').on('click', function () {
                        var text = $('#keyvalue').val();
                        isloadsearch = true;
                        searchNode(text);

                    });
                    $("#keyvalue").keyup(function () {
                        var e = event || window.event;
                        if (e.keyCode == 13) {
                            $("#seacher").trigger("click");
                            isloadsearch = true;
                        }
                        if ((e.keyCode == '46' || e.keyCode == '8' || (e.ctrlKey && e.keyCode == '86')) && $(this).val() == '' && isloadsearch) {
                            $("#seacher").trigger("click");
                            isloadsearch = false;
                        }
                    });
                    function searchNode(value) {
                        var keyType = options.data.key.name;
                        if (value === "") {
                            var allNode = treeobj.transformToArray(treeobj.getNodes());
                            treeobj.showNodes(allNode);
                            zlContext.noData($('#' + treeobj.setting.treeId), true)
                            return;
                        }
                        nodeList = treeobj.getNodesByParamFuzzy(keyType, value);
                        nodeList = treeobj.transformToArray(nodeList);
                        updateNodes(true, value, keyType);
                    };
                    function updateNodes(highlight, value, keyType) {
                        var allNode = treeobj.transformToArray(treeobj.getNodes());
                        treeobj.hideNodes(allNode);
                        for (var n = 0; n < nodeList.length; n++) {
                            findParent(treeobj, nodeList[n]);
                        }
                        treeobj.showNodes(nodeList);
                        nodeList = treeobj.getNodesByParamFuzzy(keyType, value);
                        for (var i = 0; i < nodeList.length; i++) {
                            treeobj.updateNode(nodeList[i]);
                        }
                        if (treeobj.getNodesByParam('isHidden', false, null).length == 0) {
                            zlContext.noData($('#' + treeobj.setting.treeId))
                        }
                    };
                    function findParent(zTree, node) {
                        zTree.expandNode(node, true, false, false);
                        var pNode = node.getParentNode();
                        if (pNode != null) {
                            nodeList.push(pNode);
                            findParent(zTree, pNode);
                        }

                    };
                },
                yes: function (index) {
                    var selectnode = treeobj.getSelectedNodes();
                    var cancontinue = true;
                    if (options.check != undefined && options.check.enable) {
                        selectnode = treeobj.getCheckedNodes(true);
                    }
                    if (selectnode.length == 0) {
                        zlContext.warnMsg(options.errmsg == undefined ? "请选择树节点" : options.errmsg);
                        return;
                    }
                    var ischeckleaf = options.ischeckleaf
                        , objlist = new Array();
                    for (var i = 0; i < selectnode.length; i++) {
                        var treenode = selectnode[i];
                        if (treenode.children != undefined && ischeckleaf) {
                            zlContext.warnMsg("请选择树的叶子节点！");
                            cancontinue = false;
                            return;
                        }
                        if (objlist.length == 1 && options.multselect == false) {
                            zlContext.warnMsg("只能选择一个节点！");
                            cancontinue = false;
                            return;
                        }
                        objlist.push(treenode);
                    }
                    layer.close(index);
                    if (cancontinue) {
                        if (options.selectcallback != undefined) {
                            options.selectcallback(objlist);
                        } else {
                            return objlist;
                        }
                    } else {
                        return;
                    }
                },
            });
        },
        /**局部 msg 弹窗 提示加载中 
         * 需手动关闭 $('#'+dom).find('.partialMsg').remove()
         * */
        partialMsg: function (dom, text, iconNum) {
            var width = $('#' + dom).width(),
                height = $('#' + dom).height();
            var msgHtml =
                // '<div class="layui-layer-shade partialMsg" style="position: absolute;top: 0;left: 0;width: '+ width +'px;height: '+ height +'px;z-index: 19891016; background-color: rgb(0, 0, 0); opacity: 0.1;"></div>' +
                '<div class="layui-layer layui-layer-dialog layui-layer-msg partialMsg" style="position: absolute;z-index: 19891017;">' +
                '    <div class="layui-layer-content layui-layer-padding">' +
                '        <i class="layui-layer-ico layui-layer-ico' + iconNum + '"></i>' + text +
                '    </div>' +
                '</div>';

            $('#' + dom).append(msgHtml);
            $('#' + dom).find('.partialMsg').css({
                'top': (height - $('#' + dom).find('.partialMsg').height()) / 2,
                'left': (width - $('#' + dom).find('.partialMsg').width()) / 2
            })
        },
        doCallback: function (text, data) {
            var func = eval('(' + text + ')');
            if (data) {
                func(data);
            } else {
                func();
            }

        }
    }
    exports('zlpoptree', zlpoptree);
});